<?php

class Application_Model_Propostas extends Zend_Db_Table_Abstract
{
    protected $_name = 'propostas';
    protected $_primary = 'propId';
    protected $_rowClass = 'Application_Model_Proposta';
    protected $_dependentTables = array('propostaCategory');
    
    /**
     *
     * @param int $catId
     * @return array 
     */
    public function getPropostasByCategoryId($catId)
    {
        try {
            $select = $this->select()
                           ->setIntegrityCheck(FALSE)
                           ->join('propostaCategory', 'propostaCategory.proposta_propId = propostas.evId')
                           ->where('propostaCategory.category_catId = ?', $catId);
            $propCat = $this->fetchAll($select); //Rowset di propostaCategory

            $proposte = array();
            foreach ($propCat as $pC) {
                $proposte[] = $this->getPropostaById($pC->proposta_propId);
            }
            return $proposte; //array di row di evento
            } catch (Zend_Db_Exception $eDb) { 
                throw new Zend_Db_Exception('La categoria cercata non esiste', 0, $eDb);
            }
    }
    
    public function getPropostaById($propId)
    {
        return $this->find($propId)->current();
    }
    
    public function getPropostaByIdent($propIdent)
    {
        $select = $this->select();
        $select->where('propIdent = ?', $propIdent);
        
        return $this->fetchRow($select);
    }
    
    public function getAllPropostas($paged = NULL, $order = NULL)
    {
        $select = $this->select();
        
        if (NULL != $order) {
            $select->order($order);
        }
        
        if (NULL != $paged) {
            $adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
            
            $count = $this->getNumPropostas();
            $adapter->setRowCount($count);
            
            $paginator = new Zend_Paginator($adapter);
            $paginator->setItemCountPerPage(10)
                      ->setCurrentPageNumber((int) $paged);
              return $paginator;
        }
        
        return $this->fetchAll($select);
    }
    
    public function getNumPropostas()
    {
        return $this->fetchAll()->count();
    }
    
    /**
     * Ritorna un array pulito dei titoli, per il motore di ricerca.
     * 
     * @return array of titles
     */
    public function getAllTitles()
    {
        $select = $this->select()
                       ->from('propostas', 'propTitolo');
        $titles = $this->fetchAll($select)->toArray();
        $titoli = array();
        foreach ($titles as $titolo) {
            $titoli[] = $titolo['propTitolo'];
        }
        
        return $titoli;
    }
}